/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.edmo.fastener.business;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

/**
 *
 * @author obelog
 */
public class CryptoKeyGenerator {

    public static void writeToFile(String filename, Object object) throws Exception {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;

        try {
            fos = new FileOutputStream(new File(filename));
            oos = new ObjectOutputStream(fos);
            oos.writeObject(object);
            oos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (oos != null) {
                oos.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }
    
    public static Object readFromFile(String filename) throws Exception {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        Object object = null;

        try {
            fis = new FileInputStream(new File(filename));
            ois = new ObjectInputStream(fis);
            object = ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                ois.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
        return object;
    }

    public static SecretKey generateKey() {
        SecretKey key = null;
        try {
            if (new File("secretkey.dat").exists()){
                getCryptoKey();
                key = ListofCustomersnSuppliers.getKey();
            } else {
               key = KeyGenerator.getInstance("DES").generateKey();
               writeToFile("secretkey.dat", key); 
            }
            
        } catch (Exception ex) {
            Logger.getLogger(CryptoKeyGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }
        return key;
    }
    
    public static void getCryptoKey(){
        try {
            SecretKey key = (SecretKey) readFromFile("secretkey.dat");
            ListofCustomersnSuppliers.setKey(key);
        } catch (Exception ex) {
            Logger.getLogger(CryptoKeyGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
